import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams, RequestOptions, Response } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class NotificationAddService {
    private notificationSaveUrl: string = '/water/boards/saveNotice';
    constructor(private http: Http) { }

    submitNewNotification(title: string, content: string, attachIds: string[]): Promise<any> {

        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions(headers);
        return this.http.post(this.notificationSaveUrl,
            {
                boards_content: content,
                boards_title: title,
                fileids: attachIds
            }, options).toPromise()
        .then(resp => resp.json() || {})
        .catch(this._handleException);
    }

    private _handleException(error: Response | any) {
        let errMsg: string;
        if (error instanceof Response) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify(body);
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        return Promise.reject(errMsg);
    }
}